module ApplicationHelper

	def nice_bytes( bytes, max_digits=3 )
		k = 2.0**10
		m = 2.0**20
		g = 2.0**30
		t = 2.0**40
		value, suffix, precision = case bytes
  	when 0...k
    		[ bytes, 'b', 0 ]
  	else
    		value, suffix = case bytes
      when k...m then [ bytes / k, 'KB' ]
      when m...g then [ bytes / m, 'MB' ]
      when g...t then [ bytes / g, 'GB' ]
      else          
        [ bytes / t, 'TB' ]
    	end
    	used_digits = case value
      	when   0...10   then 1
      	when  10...100  then 2
      	when 100...1000 then 3
    	end
    	leftover_digits = max_digits - used_digits
    	[ value, suffix, leftover_digits > 0 ? leftover_digits : 0 ]
		end
		"%.#{precision}f#{suffix}" % value
	end

  # check whether the request comes from our ap
  def from_ap?
    !!Terminal.find_by_ip(request.ip)
  end
  
end
